package com.baorant.apigateway.Utis;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
    /**
     * 获取Ip地址
     *
     * X-Forwarded-For - 最常用的代理转发头
     * Proxy-Client-IP - Apache 代理
     * WL-Proxy-Client-IP - WebLogic 代理
     * HTTP_CLIENT_IP - 其他代理
     * HTTP_X_FORWARDED_FOR - 其他代理格式
     * request.getRemoteAddr() - 最后备选方案
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 统一本地回环地址为 127.0.0.1
        if ("0:0:0:0:0:0:0:1".equals(ip) || "::1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }
}
